package com.zm.rpc.procedure;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;

import com.zm.rpc.procedure.pojo.ProcedureCallResult;
import com.zm.rpc.procedure.pojo.ProcedureMetadata;

public class ProcedureCaller {
    private static final Logger log = Logger.getLogger(ProcedureCaller.class);
    private ProcedureMetadata metadata;

    public ProcedureCaller(ProcedureMetadata metadata) {
        this.metadata = metadata;
    }

    public ProcedureCallResult call(Object... params){
        ProcedureCallResult result = null;
        try{
            Object procedure = this.metadata.getProcedure();
            Method targetMethod = this.metadata.getTargetMethod();
            Object resultObj = targetMethod.invoke(procedure, params);
            result = ProcedureCallResult.OK(resultObj,this.metadata);
        }catch(Exception e){
            log.error(String.format("Procedure call error,Meatadata:%s", this.metadata.toString()),e);
            result = ProcedureCallResult.ERROR(e.getMessage(), this.metadata);
        }
        return result;
    }
}
